<script setup>
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'

import {
  fetchYsyCameraDeviceDetail,
  updateYsyCameraDevice,
} from '@/api/manager/dataManage/deviceManage.js'
import VUpload from '@/components/upload/index.vue'

defineOptions({
  name: 'CameraAdd',
})

const props = defineProps({
  detail: {
    type: Object,
    default: () => {},
  },
  parkList: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['close'])

const contentLoading = ref(false)

const buttonLoading = ref(false)

const formRef = ref()

const dialogVisible = ref(false)

const title = ref('')

const type = ref('add')

const fileList = ref([])

const currentDetail = ref({})

const formRules = ref({
  nickName: [
    {
      message: '设备名称不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  position: [
    {
      message: '位置不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  imgs: [
    {
      message: '照片不能为空',
      required: false,
      trigger: ['blur', 'change'],
    },
  ],
})

const fetchDetailData = () => {
  contentLoading.value = true
  fetchYsyCameraDeviceDetail(props.detail.pkid)
    .then((res) => {
      if (res.success) {
        currentDetail.value = res.data.data
        fileList.value = res.data.imgList || []
      } else {
        ElMessage.error(res.message || '获取详情失败')
      }
    })
    .catch((err) => {
      ElMessage.error(err)
    })
    .finally(() => {
      contentLoading.value = false
    })
}

const handleCancel = () => {
  handleClose()
}

const handleSave = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      buttonLoading.value = true
      updateYsyCameraDevice({
        pkid: currentDetail.value.pkid,
        nickName: currentDetail.value.nickName,
        position: currentDetail.value.position,
        imgs: fileList.value.map((item) => item.pkid).join(','),
      })
        .then((res) => {
          if (res.success) {
            ElMessage.success('编辑成功')
            handleClose(true)
          } else {
            console.error('编辑失败', res)
            ElMessage.error(res.message || '编辑失败')
          }
        })
        .catch((err) => {
          console.error('编辑失败', err)
          ElMessage.error('编辑失败')
        })
        .finally(() => {
          buttonLoading.value = false
        })
    }
  })
}

const handleClose = (shouldRefresh) => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  fileList.value = []
  emit('close', shouldRefresh)
}

watch(
  () => props.detail,
  (val) => {
    if (val && val.pkid) {
      fetchDetailData()
    }
  },
)

watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      formRef.value?.resetFields()
    }
  },
)

defineExpose({ dialogVisible, title, type })
</script>

<template>
  <el-dialog
    class="custom-dialog"
    v-model="dialogVisible"
    :title="title"
    width="813px"
    @close="handleClose"
  >
    <div class="custom-detail" v-loading="contentLoading">
      <el-form
        ref="formRef"
        :model="currentDetail"
        :rules="formRules"
        label-position="right"
        label-width="100"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称：" prop="nickName">
              <el-input v-model="currentDetail.nickName" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="位置：" prop="position">
              <el-input
                v-model="currentDetail.position"
                placeholder="示例：120.5217,30.1782"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="照片：" prop="imgs">
              <VUpload
                v-model="fileList"
                :limit="9"
                accept=".png,.jpg,.jpeg"
                listType="picture-card"
                uploadText="点击上传图片"
              />
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
    </div>

    <template #footer>
      <el-row style="width: 100%" justify="end" align="middle">
        <el-button :loading="buttonLoading" @click="handleCancel"
          >取消</el-button
        >
        <el-button :loading="buttonLoading" type="primary" @click="handleSave"
          >保存</el-button
        >
      </el-row>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-form-item {
  width: 100%;
  margin-bottom: 0;
}
</style>
